package 图论.岛屿的最大面积_695;

import java.util.ArrayDeque;
import java.util.Deque;

/* 给你一个大小为 m x n 的二进制矩阵 grid 。

岛屿 是由一些相邻的 1 (代表土地) 构成的组合，这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0（代表水）包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿，则返回面积为 0 。

示例 1：
输入：grid =
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
输出：6
解释：答案不应该是 11 ，因为岛屿只能包含水平或垂直这四个方向上的 1 。
示例 2：

输入：grid = [[0,0,0,0,0,0,0,0]]
输出：0
* */
public class Solution {
    static boolean[][] visit;
    static int ans;
    static int count;
    static int[][] route = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    public static void main(String[] args) {
        int[][] grid = {
                {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}};

        System.out.println(maxAreaOfIsland(grid));
    }
    public static int maxAreaOfIsland(int[][] grid) {
        visit = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i ++){
            for (int j = 0; j < grid[0].length; j ++){
                if (!visit[i][j] && grid[i][j] == 1){
                    count = 1; // 如果是陆地就直接置为1，然后对剩下相邻的格子遍历有陆地则+1
                    bfs(grid, visit, i, j);
                    ans = count >= ans ? count : ans;
                }
            }
        }
        return ans;
    }

    public static void bfs(int[][] grid, boolean[][] visit, int x, int y){
        Deque<int[]> deque = new ArrayDeque<>();
        deque.offer(new int[]{x, y});
        visit[x][y] = true;
        while (!deque.isEmpty()){
            int[] t = deque.poll();
            for (int i = 0; i < 4; i ++){
                int dx = route[i][0] + t[0];
                int dy = route[i][1] + t[1];
                if (dx < 0 || dy < 0 || dx >= grid.length || dy >= grid[0].length){
                    continue;
                }
                if (visit[dx][dy] == false && grid[dx][dy] == 1){
                    deque.offer(new int[]{dx, dy});
                    visit[dx][dy] = true;
                    count ++; // 唯一的变化是需要计数
                }
            }
        }
    }
}
